﻿using System.Security.Cryptography;
using System.Text;

namespace ShareHelper
{
    /// <summary>
    /// MD5 生成静态类
    /// </summary>
    public static class Md5Util
    {
        private static MD5 MD5 { get; }

        static Md5Util()
        {
            MD5 = MD5.Create();
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">加密内容</param>
        /// <param name="Lower">是否小写,默认小写</param>
        /// <returns></returns>
        public static string GetMd5Str(this string str, bool Lower = true)
        {
            return GetMd5Str(Encoding.UTF8.GetBytes(str), Lower);
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="source">加密内容</param>
        /// <param name="Lower">是否小写,默认小写</param>
        /// <returns></returns>
        public static string GetMd5Str(this byte[] source, bool Lower = true)
        {
            return GetMd5Str(source, 0, source.Length, Lower);
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="source">加密内容</param>
        /// <param name="offset"> 字节数组中的偏移量，从该位置开始使用数据。</param>
        /// <param name="count">数组中用作数据的字节数。</param>
        /// <param name="Lower">是否小写,默认小写</param>
        /// <returns></returns>
        public static string GetMd5Str(this byte[] source, int offset = 0, int count = 0, bool Lower = true)
        {
            return HexHelper.ByteToHexStr(MD5.ComputeHash(source, offset, count), Lower);
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="str">加密内容</param>
        /// <returns></returns>
        public static byte[] GetMd5(this string str)
        {
            return GetMd5(Encoding.UTF8.GetBytes(str));
        }

        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="source">加密内容</param>
        /// <param name="offset"> 字节数组中的偏移量，从该位置开始使用数据。</param>
        /// <param name="count">数组中用作数据的字节数。</param>
        /// <returns></returns>
        public static byte[] GetMd5(this byte[] source, int offset = 0, int count = 0)
        {
            if (count == 0)
            {
                count = source.Length - offset;
            }
            return MD5.ComputeHash(source, offset, count);
        }
    }
}